package com.xiaolin.Thread.synchronization;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName ReentrantLockTest
 * @Description ReentrantLock 实现线程安全
 * @Detail detail
 * @Author MyPC
 * @Date 2020/12/1
 * @Version 1.0
 */
public class ReentrantLockTest {
    public static void main(String[] args) {
        // 开启两个线程
       OneThread thread1=new OneThread();
       OneThread thread2=new OneThread();
       thread1.start();
       thread2.start();
    }
}

class OneThread extends Thread{
    private static int ticket=100;
    private static ReentrantLock lock=new ReentrantLock();

    @Override
    public void run() {
        for (int i=0;i<100;i++){
            buy();
        }
    }

    public static void buy(){
        try {
            lock.lock();
            if(ticket==0){
                return;
            }
            // 睡眠10毫秒，如果不加锁，那么当票数为1时，可能很多线程就会进入到这里
            Thread.sleep(10L);
            System.out.println("买到了第"+ticket--+"张票");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}


